package io.serializable;

import framework.AbstractTest;
import utils.Log;

import java.io.*;
import java.util.Random;


/**
 * Created by shane on 2018/5/28.
 */
public class Worm extends AbstractTest implements Serializable {


    private static final long serialVersionUID = 8779281884319190043L;
    private static final String TAG = "Worm";

    private static Random rand = new Random(47);

    private Data[] d = {
          new Data(rand.nextInt(10)),
          new Data(rand.nextInt(10)),
          new Data(rand.nextInt(10)),
    };

    private Worm next;
    private char c;

    public Worm(int i, char x) {
        Log.vn("Worm constructor: " + i);
        c = x;
        if (--i > 0) {
            next = new Worm(i, (char)(x+1));
        }
    }

    public Worm() {
        Log.vn("Default constructor: ");
    }


    public String toString() {
        StringBuilder sb = new StringBuilder(":");
        sb.append(c);
        sb.append("(");
        for (Data dat : d) {
            sb.append(dat);
        }
        sb.append(")");

        if (next != null) {
            sb.append(next);
        }

        return sb.toString();
    }

    @Override
    public void test(String[] args) {
        super.test(args);
        String outFilePath = getDefTempFile(args);

        try {
            Worm w = new Worm(6, 'a');
            Log.vn("w = " + w);
            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(outFilePath));
            out.writeObject("Worm storage\n");
            out.writeObject(w);
            out.close(); // Also flushes output

            ObjectInputStream in = new ObjectInputStream(new FileInputStream(outFilePath));
            String s = (String)in.readObject();
            Worm w2 = (Worm) in.readObject();
            Log.vn(s + "w2 = " + w2);


            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            ObjectOutputStream out2 = new ObjectOutputStream(bout);
            out2.writeObject("Worm storage\n");
            out2.writeObject(w);
            out2.flush();

            ObjectInputStream in2 = new ObjectInputStream(new ByteArrayInputStream(bout.toByteArray()));
            s = (String) in2.readObject();
            Worm w3 = (Worm) in2.readObject();
            Log.vn(s + "w3 = " + w3);

        } catch (Exception e) {

        }

    }

    @Override
    protected String getTag() {
        return TAG;
    }
}
